package blipappeal;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.wave.api.*;
import blipappeal.util.FileUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class BlipAppealServlet extends AbstractRobotServlet {

	public static String welcomeUrl = null;
	public final static String upDownUrl = "gadgets/updown/gadget.xml";
	public final static String sliderUrl = "gadgets/slider/gadget.xml";
	
	private String m_strRobotUrl = null;
	private String m_strHostUrl = null;
	private static String m_strSiteRoot = null;
	private static String m_strContextName = null;
	private String[] m_astrGadgetList = null;
	
	
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);

		if (m_strSiteRoot == null)
		{
			m_strSiteRoot = this.getServletContext().getRealPath("");
			m_strSiteRoot = m_strSiteRoot.replace(File.separatorChar, '/');
			if (!m_strSiteRoot.endsWith("/"))
			{
				m_strSiteRoot += "/";
			}
		}

		if (m_strContextName == null)
		{
			m_strContextName = this.getServletContext().getServletContextName();
		}
		
		m_astrGadgetList = getGadgetList();
	}

  @Override
  public void processEvents(RobotMessageBundle bundle) {
	Wavelet wavelet = bundle.getWavelet();
              
    if (bundle.wasSelfAdded()) {
      Blip blip = wavelet.appendBlip();
      TextView textView = blip.getDocument();
      textView.append("Let the voting begin!");
      textView.appendElement(new Gadget(welcomeUrl));
    }
       
    for (Event e: bundle.getEvents()) {
      if (e.getType() == EventType.BLIP_SUBMITTED) {    
    	  //String myGadgetUrl = "http://mister-roboto-1.appspot.com/gadgets/updown/gadget.xml";
    	  String myGadgetUrl = m_strHostUrl + upDownUrl;
          Blip blip = e.getBlip();

          //TODO proper error handling
          assert(blip.isDocumentAvailable());
          TextView textView = blip.getDocument();
          GadgetView gadgetView = textView.getGadgetView();

          if ((gadgetView == null) || (gadgetView.getGadget(myGadgetUrl) == null)) {
              textView.appendElement(new Gadget(myGadgetUrl));
              //textView.insertElement(0, new Gadget(myGadgetUrl));
          }
          else {
        	int cumAvg = Score.getBlipScore(blip, myGadgetUrl);
        	// let's embolden our high scoring blips
        	// Score.emboldenBlip(blip, cumAvg);
          }
        }
    }
  }
  
  @Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		
		Writer writerDest = null;
		try
    {
			writerDest = resp.getWriter();
			writeWelcomeGadget(m_astrGadgetList, writerDest);
    }
		finally
		{
			FileUtil.close(writerDest);
		}
	}
  
  public String[] getGadgetList()
	{
		ArrayList<String> arrGadgetFiles = new ArrayList<String>();
		
		File fileGadgetFolder = new File(m_strSiteRoot, "gadgets");
		File[] afileGadgets = fileGadgetFolder.listFiles();
		for (File fileGadget : afileGadgets)
		{
			if (fileGadget.isDirectory())
			{
				String strName = fileGadget.getName();
				
				if (!strName.equals("welcome"))
				{
					arrGadgetFiles.add(fileGadget.getName());
				}
			}
		}
		
		return arrGadgetFiles.toArray(new String[0]);

	}
  
  public void writeWelcomeGadget(String[] astrGadgetList, Writer writerDest)
	{
		
		Hashtable mapParams = new Hashtable();
  	mapParams.put("GadgetList", astrGadgetList);

		Configuration cfg = new Configuration();
    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
		
    try
    {
      File fileTemplateFolder = new File(m_strSiteRoot, "gadgets/welcome");
      cfg.setDirectoryForTemplateLoading(fileTemplateFolder);  

      Template tmplGadget = cfg.getTemplate("gadget.xml"); 
      tmplGadget.process(mapParams, writerDest);
		} 
		catch (FileNotFoundException exFile)
		{
			// TODO Auto-generated catch block
			exFile.printStackTrace();
		} 
		catch (IOException exIO)
		{
			// TODO Auto-generated catch block
			exIO.printStackTrace();
		} catch (TemplateException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally
		{
			FileUtil.close(writerDest);
		}
		

	}
  
  @Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		if (m_strRobotUrl == null)
		{
			m_strRobotUrl = req.getRequestURL().toString();
			welcomeUrl = m_strRobotUrl;
			URL urlHost = new URL(m_strRobotUrl);
			
			String strPort = "";
			if (urlHost.getPort() > 0)
			{
				strPort = ":" + urlHost.getPort();
			}
			
			m_strHostUrl = urlHost.getProtocol() + "://" + urlHost.getHost() + strPort + "/";
			if (m_strRobotUrl.endsWith("/"))
			{
				m_strRobotUrl += "/";
			}
		}
		
		super.service(req, resp);
	}
}